package models

import (
	"errors"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type IndicationModel struct {
	BaseModel `xorm:"extends"`
	Name      string `json:"name"`
}

func (sm *IndicationModel) TableName() string {
	return "indication"
}

func (sm *IndicationModel) Insert() error {
	_, err := app.DB().Insert(sm)
	if err != nil {
		return err
	}
	return nil
}

func (sm *IndicationModel) SelectByName(name string) (*IndicationModel, error) {
	doc := &IndicationModel{}
	has, err := app.DB().Where("name = ?", name).Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by IndicationModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *IndicationModel) SelectByNameAll(name string) ([]IndicationModel, error) {
	doc := make([]IndicationModel, 0)
	if name == "" {
		return nil, nil
	}
	s := app.DB().Table("indication").OrderBy("name asc").Where("name like ?", "%"+name+"%")

	_, err := s.FindAndCount(&doc)
	if err != nil {
		return nil, err
	}
	return doc, err
}

func (sm *IndicationModel) SelectById(id string) (*IndicationModel, error) {
	doc := &IndicationModel{}
	has, err := app.DB().Where("id = ?", id).Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by IndicationModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *IndicationModel) UpdateData(req *IndicationModel, id string) error {
	_, err := app.DB().Where("id = ?", id).Cols("name").Update(req)
	if err != nil {
		middlewares.Logger.Println("IndicationModel Update failed ", err)
		return errors.New("数据修改失败")
	}
	return nil
}

func (sm *IndicationModel) SelectAll() ([]IndicationModel, error) {
	doc := make([]IndicationModel, 0)
	s := app.DB().Table("indication").OrderBy("name asc").Where("deleted_at is null")

	_, err := s.FindAndCount(&doc)
	if err != nil {
		return nil, err
	}
	return doc, err
}

func (sm *IndicationModel) DeleteIndication(id string) error {
	doc := &IndicationModel{}
	_, err := app.DB().Where("id = ?", id).Delete(doc)
	if err != nil {
		middlewares.Logger.Println("delete by DeleteIndication", err)
		return err
	}
	return err
}
